#!/usr/bin/env python
# -*- coding: utf-8 -*-
# created at 30.04.2011

# This software is distributed under the BSD license.
# http://www.opensource.org/licenses/bsd-license.php 
# Copyright © 2011, Oleg Churkin

"""
This module is intended to:

    * Convert all code from Python 2 to Python 3 if required.
    * Run unittests.
    * Rebuild the documentation.
"""


import unittest
import sys
import os

BUILDING_ERROR = 1
BUILDING_SUCCESS = 0


def execute_unittests():
    """Execute unittests from tests.basic_tests.py"""
    print("Running unittests.")
    from tests.basic_tests import Test
    suite = unittest.TestLoader().loadTestsFromTestCase(Test)
    results = unittest.TextTestRunner(verbosity=2).run(suite)
    return results.wasSuccessful() 


def building_docs():
    """Creating Sphinx documentation"""
    print("Creating documentation.")
    import sphinx
    docs_dir = os.path.join(os.path.dirname(__file__), "docs")
    doc_trees_dir = os.path.join(docs_dir, "doctrees")
    source_dir = os.path.join(docs_dir, "source")
    build_dir = os.path.join(docs_dir, "html")
    arguments = []
    arguments.append("-a") # rewrite all files
    arguments.append("-b")
    arguments.append("html") # html builder
    arguments.append("-d")
    arguments.append(doc_trees_dir) # cached environment and doctree files
    arguments.append(source_dir) # source
    arguments.append(build_dir) # build dir
    return sphinx.main(arguments)
     

def execute_2to3():
    """Converts all scripts to Python 3 using 2to3 library."""
    
    if sys.version_info >= (3,):
        print("Python 3 is detected, so let's convert the code.")
        
        import lib2to3.refactor
        import lib2to3.pgen2

        fixers = lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
        refactorer = lib2to3.refactor.RefactoringTool(fixers)
        
        current_dir = os.path.dirname(__file__)
        print(("Starting code refactoring in '{0}'.".format(current_dir)))
        try:
            refactorer.refactor_dir(current_dir, write=True)
        except lib2to3.pgen2.parse.ParseError as ex:
            print("Probably the code was already converted.")     


def main():
    print("Building 'easylogger'.")
    try:
        execute_2to3()
    except Exception as ex:
        print(ex)
        return BUILDING_ERROR
    if not execute_unittests():
        print("Some unittests were failed.")
        return BUILDING_ERROR
    if building_docs():
        print("There are some errors occurred when building documentation.")
        return BUILDING_ERROR
    print("Building is completed successfully.")
    return BUILDING_SUCCESS

        
if __name__ == '__main__':
    sys.exit(main())
